package com.backend.plat.sa.controller;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.backend.dto.FunctionRelateMenuDto;
import com.backend.dto.PermissionFunctionDto;
import com.backend.dto.PermissionMenusDto;
import com.backend.dto.PermissionRelateRoleDto;
import com.backend.dto.RolesDto;
import com.backend.dto.TreeDto;
import com.google.gson.reflect.TypeToken;
import com.oxygen.constants.Constant;
import com.oxygen.dto.ApiFinalResponse;
import com.oxygen.enums.BackendApiMethodEnum;
import com.oxygen.util.JsonUtil;
import com.oxygen.web.WebHelper;

/**
 * 前台用户管理
 * 
 * @author json
 */
@Controller
@RequestMapping(value = "/roles")
public class BackendRolesAction extends BaseAction {

	private static final String page_edit = "/roles/edit";

	/**
	 * 进入新增页面
	 * 
	 * @param req
	 * @param rsp
	 */
	@RequestMapping(value = "/add")
	public String add(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			// 得到功能列表
			Map<String, Object> appendMap1 = new HashMap<String, Object>();
			String json1 = this.callApi(BackendApiMethodEnum.USER_GETFUNCTION,
					appendMap1, req);
			Type type1 = new TypeToken<Map<String, ApiFinalResponse<List<PermissionFunctionDto>>>>() {
			}.getType();
			Map<String, ApiFinalResponse<List<PermissionFunctionDto>>> retMap1 = JsonUtil
					.jsonToObject(json1, type1);
			req.setAttribute("apiRsp", retMap1
					.get(BackendApiMethodEnum.USER_GETFUNCTION.getCode()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page_edit;
	}

	@RequestMapping(value = "/search")
	public String search(HttpServletRequest req, HttpServletResponse rsp) {
		WebHelper.setRequestAttributesFromRequestParam(req);
		return "/roles/search";
	}

	@RequestMapping(value = "/list")
	public String list(HttpServletRequest req, HttpServletResponse rsp) {
		String menuId = req.getParameter("menuId");
		req.setAttribute("menuId", menuId);
		Map<String, Object> appendMap = new HashMap<String, Object>();
		appendMap.put(Constant.PAGE, req.getParameter(Constant.PAGE));
		appendMap.put(Constant.PAGE_SIZE, req.getParameter(Constant.PAGE_SIZE));
		String json = this.callApi(BackendApiMethodEnum.USER_GETROLES,
				appendMap, req);
		Type type = new TypeToken<Map<String, ApiFinalResponse<List<RolesDto>>>>() {
		}.getType();
		Map<String, ApiFinalResponse<List<RolesDto>>> retMap = JsonUtil
				.jsonToObject(json, type);

		if (retMap != null) {
			retMap.get(BackendApiMethodEnum.USER_GETROLES.getCode())
					.getResults();
			req.setAttribute("apiRsp",
					retMap.get(BackendApiMethodEnum.USER_GETROLES.getCode()));

		}
		WebHelper.setRequestAttributesFromRequestParam(req);
		return "/roles/list";
	}

	/**
	 * 进入编辑角色页面
	 * 
	 * @param id
	 * @param req
	 * @param rsp
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}")
	public String edit(@PathVariable String id, HttpServletRequest req,
			HttpServletResponse rsp) {
		// 得到角色信息
		Map<String, Object> appendMap = new HashMap<String, Object>();
		appendMap.put("id", id);
		String json = this.callApi(BackendApiMethodEnum.USER_QUERYROLESBYID,
				appendMap, req);
		Type type = new TypeToken<Map<String, ApiFinalResponse<RolesDto>>>() {
		}.getType();
		Map<String, ApiFinalResponse<RolesDto>> retMap = JsonUtil.jsonToObject(
				json, type);
		RolesDto roles = retMap.get(
				BackendApiMethodEnum.USER_QUERYROLESBYID.getCode())
				.getResults();
		List<PermissionRelateRoleDto> menuList = roles.getMenuList(); // 角色的菜单集合
		List<String> menuIdList = new ArrayList<String>();
		for (PermissionRelateRoleDto permissionRelateRoleDto : menuList) {
			menuIdList.add(permissionRelateRoleDto.getMenuId().toString());
		}
		roles.setCheckedMenuId(StringUtils.join(
				(String[]) menuIdList.toArray(new String[menuIdList.size()]),
				","));
		if (retMap != null
				&& retMap.get(BackendApiMethodEnum.USER_QUERYROLESBYID
						.getCode()) != null) {
			req.setAttribute("roles", roles);
		}

		// 得到功能列表
		Map<String, Object> appendMap1 = new HashMap<String, Object>();
		appendMap1.put(Constant.PAGE, req.getParameter(Constant.PAGE));
		appendMap1.put(Constant.PAGE_SIZE, 1000);
		String json1 = this.callApi(BackendApiMethodEnum.USER_GETFUNCTION,
				appendMap1, req);
		Type type1 = new TypeToken<Map<String, ApiFinalResponse<List<PermissionFunctionDto>>>>() {
		}.getType();
		Map<String, ApiFinalResponse<List<PermissionFunctionDto>>> retMap1 = JsonUtil
				.jsonToObject(json1, type1);
		List<PermissionFunctionDto> permissionFunctionList = retMap1
				.get(BackendApiMethodEnum.USER_GETFUNCTION.getCode()).getResults();
		req.setAttribute("apiRsp",
				retMap1.get(BackendApiMethodEnum.USER_GETFUNCTION.getCode()));
		return "/roles/edit";
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public void save(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			String menuIds = req.getParameter("ids");
			String funIds = StringUtils.join(
					req.getParameterValues("list-checkbox"), ",");
			paramMap.put("menuIds", menuIds);
			paramMap.put("funIds", funIds);
			WebHelper.outputJson(this.callApi(
					BackendApiMethodEnum.USER_OPERATIONROLES, paramMap, req),
					rsp);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新角色
	 * 
	 * @param req
	 * @param rsp
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public void update(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			String roleId = req.getParameter("roleId");
			Map<String, Object> paramMap = new HashMap<String, Object>();
			String menuIds = req.getParameter("ids");
			String funIds = StringUtils.join(
					req.getParameterValues("list-checkbox"), ",");
			paramMap.put("menuIds", menuIds);
			paramMap.put("funIds", funIds);
			paramMap.put("id", roleId);
			WebHelper.outputJson(this.callApi(
					BackendApiMethodEnum.USER_UPDATEROLES, paramMap, req), rsp);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/***
	 * 删除角色
	 * 
	 * @return
	 */
	@RequestMapping(value = "/delete")
	public void deleteMenu(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			Map<String, Object> appendMap = new HashMap<String, Object>();
			WebHelper
					.outputJson(this.callApi(
							BackendApiMethodEnum.USER_DELETEROLES, appendMap,
							req), rsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 根据菜单ID得到功能列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getFunctionListByMenuId")
	public String getFunctionListByMenuId(HttpServletRequest req,
			HttpServletResponse rsp) {
		try {
			String menuId = req.getParameter("id");
			String roleId = req.getParameter("roleId");
			// 根据菜单ID得到菜单的功能列表
			Map<String, Object> appendMap = new HashMap<String, Object>();
			appendMap.put("menuId", menuId);
			String json = this.callApi(
					BackendApiMethodEnum.USER_GETFUNCTIONLISTBYMENUID,
					appendMap, req);
			Type type = new TypeToken<Map<String, ApiFinalResponse<List<FunctionRelateMenuDto>>>>() {
			}.getType();
			Map<String, ApiFinalResponse<List<FunctionRelateMenuDto>>> retMap = JsonUtil
					.jsonToObject(json, type);
			if (retMap != null) {
				req.setAttribute("apiRsp", retMap
						.get(BackendApiMethodEnum.USER_GETFUNCTIONLISTBYMENUID
								.getCode()));
			}
			// 得到这个角色的菜单关联的功能
			req.setAttribute("menuId", menuId);
			req.setAttribute("roleId", roleId);

			Map<String, Object> appendMap1 = new HashMap<String, Object>();
			appendMap1.put("menuId", menuId);
			String json1 = this.callApi(
					BackendApiMethodEnum.USER_GETPERMISSIONRELATEROLELIST,
					appendMap, req);
			Type type1 = new TypeToken<Map<String, ApiFinalResponse<List<PermissionRelateRoleDto>>>>() {
			}.getType();
			Map<String, ApiFinalResponse<List<PermissionRelateRoleDto>>> retMap1 = JsonUtil
					.jsonToObject(json1, type1);
			if (retMap1 != null) {
				List<PermissionRelateRoleDto> permissionRelateRoleList = retMap1
						.get(BackendApiMethodEnum.USER_GETPERMISSIONRELATEROLELIST
								.getCode()).getResults();
				req.setAttribute("permissionRelateRoleList",
						permissionRelateRoleList);
			}
			WebHelper.setRequestAttributesFromRequestParam(req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/roles/functionListPanel";
	}

	/**
	 * ajax得到菜单,功能树
	 */
	@ResponseBody
	@RequestMapping(value = "/getMenuFunctionTree")
	public void getMenuFunctionTree(HttpServletRequest req,
			HttpServletResponse rsp) {
		Map<String, Object> appendMap = new HashMap<String, Object>();
		String json = this.callApi(BackendApiMethodEnum.USER_GETMENU,
				appendMap, req);
		Type type = new TypeToken<Map<String, ApiFinalResponse<List<PermissionMenusDto>>>>() {
		}.getType();
		Map<String, ApiFinalResponse<List<PermissionMenusDto>>> retMap = JsonUtil
				.jsonToObject(json, type);
		List<TreeDto> treeDtoList = new ArrayList<TreeDto>();
		if (retMap != null) {
			List<PermissionMenusDto> permissionMenusList = retMap.get(
					BackendApiMethodEnum.USER_GETMENU.getCode()).getResults();

			for (PermissionMenusDto permissionMenusDto : permissionMenusList) {
				TreeDto treeDto = new TreeDto();
				treeDto.setId(permissionMenusDto.getId().toString());
				if (permissionMenusDto.getParentId() == 0) {
					treeDto.setParent("#");
				} else {
					treeDto.setParent(permissionMenusDto.getParentId()
							.toString());
				}
				treeDto.setText(permissionMenusDto.getName());
				treeDtoList.add(treeDto);
			}
		}
		String str = JSON.toJSONString(treeDtoList);
		WebHelper.outputJson(str, rsp);
	}

	/**
	 * 保存菜单的关联功能
	 */
	@ResponseBody
	@RequestMapping(value = "/saveMenuFun")
	public void saveMenuFun(HttpServletRequest req, HttpServletResponse rsp) {
		try {
			Map<String, Object> paramMap = new HashMap<String, Object>();
			String funIds = StringUtils.join(
					req.getParameterValues("list-checkbox"), ",");
			paramMap.put("funIds", funIds);
			paramMap.put("roleId", req.getParameter("roleId"));
			WebHelper.outputJson(this.callApi(
					BackendApiMethodEnum.USER_BATCHSAVEPERMISSIONRELATEROLE,
					paramMap, req), rsp);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
